#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main(int argc, char* argv[])
{
    // wc -c a.txt  wc -w a.txt  wc -l a.txt  wc a.txt
    if(argc < 2)
    {
        fprintf(stderr, "eg : wc -c a.txt | wc a.txt\n");
        exit(1);
    }
    // 先 wc a.txt 的执行逻辑
    int count_c = 0;
    int count_w = 0;
    int count_l = 0;

    //路径 文件
    FILE* file = fopen(argv[1], "r");
    if(!file)
    {
        fprintf(stderr,"fopen failed : %s\n", argv[1]);
        // exit(1);
        return EXIT_FAILURE;
    }
    int num = 0;
    //0 表示不在单词中  1 表示在单词中
    int in_word = 0;
    while((num = fgetc(file)) != EOF)
    {
        count_c++;
        if(num == '\n')
            count_l++;
        if(isalnum(num))
        {
            if(!in_word)
            {
                count_w++;
                in_word = 1;
            }
        }else
        {
            in_word = 0;
        }
    }
    if(argc == 2)
    {
        //读文件，计数，打印 行数 字符数 单词数
        printf(" %d %d %d %s\n", count_l, count_w, count_c, argv[1]);
    }
    if(argc == 3)
    {
        if(!strcmp(argv[2], "-l"))
        {
            printf("%d  %s\n", count_l, argv[1]);
        }
        else if(!strcmp(argv[2], "-w"))
        {
            printf("%d  %s\n", count_w, argv[1]);
        }
        else if(!strcmp(argv[2], "-c"))
        {
            printf("%d  %s\n", count_c, argv[1]);
        }
        else{
            printf("输入指令错误\n");
        }
    }
    return 0;
}